package cn.youwan.market.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;

import cn.youwan.market.MainActivity;
import cn.youwan.market.http.HttpClientFactory;


public class HttpRequestUtils {

	public static String request(String urlStr,List<NameValuePair> params) {
		String response = "";
		BufferedReader br = null;
		try {
			StringBuilder sb=new StringBuilder("");
			if(params!=null && params.size()>0){
				int len=params.size();
				NameValuePair valPair=null;
				if(urlStr.indexOf("?")==-1){
					sb.append("?");
				}
				for(int i=0;i<len;i++){
					valPair=params.get(i);
					sb.append(valPair.getName()).append("=").append(valPair.getValue());
					if(i+1<len){
						sb.append("&");
					}
				}
			}

			System.out.println("getDownLoadURL:"+urlStr + sb.toString());
			URL url = new URL(urlStr + sb.toString());
			URLConnection urlconn = url.openConnection();
			HttpURLConnection httpConnection = (HttpURLConnection) urlconn;
			httpConnection.setConnectTimeout(1000000);
			httpConnection.setReadTimeout(1000000);
			br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), "UTF-8"));
			String line = "";
			while ((line = br.readLine()) != null) {
				response += line;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
				}
			}

		}
		return response;
	}
	
	public static String post(String url, List<NameValuePair> params) {
		String response = null;
		try {
			HttpPost post = new HttpPost(url);
			if (params != null && params.size() > 0) {
				post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			}
			//增加请求头，以后在家
			//TODO
//			String userAgent = MainActivity.USER_AGENT;
//			post.setHeader("user-agent", userAgent);
			HttpContext httpContext = new BasicHttpContext();
			HttpClient client = HttpClientFactory.newInstance(120000);
			HttpResponse httpResponse = client.execute(post, httpContext);
			StatusLine statusLine = httpResponse.getStatusLine();
			final int status = statusLine.getStatusCode();
			if (status != HttpStatus.SC_OK
					|| status == HttpStatus.SC_NOT_MODIFIED) {
				String message = "HTTP Response code: "
						+ statusLine.getStatusCode() + " - "
						+ statusLine.getReasonPhrase();
				throw new IOException(message);
			}
			HttpEntity httpEntity = httpResponse.getEntity();
			InputStream is = httpEntity.getContent();

			response = inputStream2String(is);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		return response;

	}
	
	private static String inputStream2String(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}
	
	
}
